package com.ldc.webview.activity

import android.view.KeyEvent
import android.widget.LinearLayout
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.just.agentweb.AgentWeb
import com.ldc.commonlibs.conf.AppConf
import com.ldc.commonlibs.conf.RouteConf
import com.ldc.commonlibs.uts.ViewModelUtils
import com.ldc.commonres.common.VBMActivity
import com.ldc.webview.databinding.WbActivityMainBinding
import com.ldc.webview.viewmodel.WbViewModelBase


@Route(path = RouteConf.WebViewRoute.startEnter)
class WbActivity : VBMActivity<WbActivityMainBinding, WbViewModelBase>() {

    @JvmField
    @Autowired(name = AppConf.ARG_URL)
    var url: String = "https://www.baidu.com"

    @JvmField
    @Autowired(name = AppConf.ARG_TITLE)
    var title: String = "百度"

    private var agentWeb: AgentWeb? = null

    override fun main() {
        viewBind?.topBar?.also { top ->
            top.flBack.setOnClickListener { finish() }
            top.tvName.text = title
        }
        agentWeb = viewBind?.agentView.run {
            AgentWeb.with(this@WbActivity)
                .setAgentWebParent(this as LinearLayout, LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .createAgentWeb()
                .ready()
                .go(url)
        }
    }

    override fun createViewBinding(): WbActivityMainBinding =
        WbActivityMainBinding.inflate(layoutInflater)

    override fun createViewModel(): WbViewModelBase = ViewModelUtils.create(this, WbViewModelBase::class.java)


    override fun onPause() {
        agentWeb?.webLifeCycle?.onPause()
        super.onPause()
    }

    override fun onResume() {
        agentWeb?.webLifeCycle?.onResume()
        super.onResume()
    }

    override fun onDestroy() {
        agentWeb?.webLifeCycle?.onDestroy()
        super.onDestroy()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (agentWeb?.handleKeyEvent(keyCode, event)!!) {
            true;
        } else
            super.onKeyDown(keyCode, event)
    }
}